<?php

/**
 * 1. 确定没有患病的病
 * 2. 选择要检查的病
 *    2.1是否已经问卷调查过
 *    2.1 查找出体检信息并保存 memecha[tijian]中
 *    2.3 是否有需要调差的诱因
 * 2. 查找需要做问卷调查的诱因（体检表字段）
 *    3.1 诱因list
 * 3. 组合问卷list保存在session中
 * 4. 每一次问卷对应的诱因进行保存 保存到memecha[tijian]
 * 5. memecha[tjian] * 权重  （权重表）
 */
//require_once 'QuestionController.php';

class DiseaseController extends Controller
{

    /**
     * 风险评估入口，根据疾病做相应处理
     * @param $disid 疾病种类，默认高血压
     */
    public $layout = "\\layouts\disease_mobile";
    private $diseaseService = null;

    function __construct($id)
    {
        parent::__construct($id);
        $this->diseaseService = new DiseaseService();
    }

    /**
     * 所有疾病的患病风险
     */
    public function actionEvaluatelist()
    {
        $result = $this->diseaseService->getEvaluateList($_GET);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        echo JSONHelper::retInfo(true, $result);
    }

    /**
     * 判断是否能够进行风险评估
     */
    public function actionBeEvaluated()
    {
        $result = $this->diseaseService->getBeEvaluated($_GET);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        } else {
            JSONHelper::echoJSON(true);
        }
    }

    /**
     * 风险评估前导页
     */
    public function actionEvaluateLeaderPage($uid)
    {
        $result = $this->diseaseService->getEvaluateList($_GET);
        $firsttime = 0;
        if (is_int($result)) {
            $firsttime = 1;
        }
        $this->render("evaluateLeaderPage", array("uid" => $uid, "firsttime" => $firsttime));
    }

    /**
     * 所有疾病的患病风险,列成图表
     */
    public function actionEvaluatelistAsChart()
    {
        $result = $this->diseaseService->getEvaluateList($_GET);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        $this->renderPartial("evaluatelistaschart", array("result" => $result));
    }

    /**
     * 风险评估总览页面
     */
    public function actionEvaluatelistShow()
    {
        //从疾病详情结果页回退到疾病评估列表页
//        Yii::app()->session['procession']='forward';
        if(isset($_GET['uid'])&&$_GET['uid'] > 0){
            $result = $this->diseaseService->getEvaluateList($_GET);
        }else{
            $result = $this->diseaseService->getEvaluateListBySession();
        }

        if (is_int($result)) {
            if ($result === JSONHelper::ERROR_EVALUATE_NOINFO) {
                $uid = $_GET["uid"];
                $this->redirect($this->createUrl("app/question/all", array("uid" => $uid)));
            }
            JSONHelper::echoJSON(false, $result);
        }
        $this->renderPartial("evaluatelistshow", array("result" => $result));
    }
    /**
     * 未登录用户风险评估
     */

    /**
     * 直接出评估结果,不检测是否回答了问卷
     */
    public function actionEvaluatebyid()
    {
        if (!isset($_GET["uid"]) || $_GET["uid"] <= 0) {
            $this->render("evaluateUnLogin");
            Yii::app()->end();
        }
        //从问卷进入评估函数
        $result = $this->diseaseService->getEvaluateById($_GET);
        if (is_int($result)) {
            throw new CHttpException(200, "评估出错", $result);
        }
        $this->render("evaluatebyid", array("result" => $result));
    }
    /**
     * 疾病风险评估，针对某一个疾病哦
     */


    /**
     * $user
     * Enter description here ...
     * @param unknown_type $disid
     * @param unknown_type $user
     * return array("sports_sug_arr" => array("safe_sug_arr" => array(""=>evaluate_suggestion_sport
     *                                                                  )
     *                                          "safe_sug_other_arr" => array(""=>evaluate_suggestion_sport->item
     *                                                                        )
     *                                            )
     *                )
     */
    public function actionAnalysis()
    { //$user = array('id' => 2, 'username' => 'test')
        if (!isset($_GET["uid"]) || !isset($_GET["disid"])) {
            echo '非法请求';
            return;
        }
        $disid = $_GET["disid"];
        $userid = $_GET["uid"];
        $token = isset($_GET["token"]) ? $_GET["token"] : null;

        //安全检测
        if ($token === null) {
            JSONHelper::echoJSON(false, JSONHelper::ERROR_ILLEGAL_REQUEST);
        }
        $uri = "disease/" . $this->getAction()->getId();
        if ($token != SafeVerfiy::getKey($userid, $uri)) {
            JSONHelper::echoJSON(false, JSONHelper::ERROR_ILLEGAL_REQUEST);
        }

        if (isset($_GET['quesagain'])) {
            $this->questionAgain();
        }

        $dis = new Disease($disid); //$items中包含了所有的该疾病的诱因

        $items = $dis->getElements();

        if (!count($items)) {
            //错误，该疾病没有相关的诱因
            //            JSONHelper::echoJSON(false,  JSONHelper::ERROR_INTERNAL);
            echo '内部错误';
            return;
        }

        $userinfo = Disease::getUserInfo($userid);

        $ques = array();
        foreach ($items as $key => $element_name) {
            $col = $element_name;
            //用户所有信息列默认为空，这里判断如果为空则表示信息不全，需要提供问题
            if ($userinfo->$col === NULL) {
                $ret = EvaluateQuestionElement::model()->find("element_name=:name", array(":name" => $element_name));
                if (!empty($ret)) {
                    array_push($ques, $ret->question_id);
                }
            }
        }
        $hum_heal_ret = EvaluateHumanHealthTag::model()->findByPk($userid);
        if ($hum_heal_ret != null && $hum_heal_ret->teststatus == 0) {
            $ret = EvaluateQuestionnaire::model()->findAllByAttributes(array("questype" => 5));
            if (!empty($ret)) {
                foreach ($ret as $it) {
                    array_push($ques, $it->id);
                }
            }
            $hum_heal_ret->teststatus = 1;
            $hum_heal_ret->update();
        }
        if (count($ques)) {
            $ques = array_values(array_unique($ques));
            $ques_str = implode(",", $ques);
            $this->redirect($this->createUrl("app/question/question", array(
                "ques_str" => $ques_str, "disid" => $disid, "uid" => $userid, "token" => $token,
            )));
        } else {
            //直接风险评估
            //$userinfo = $this->getUserInfo($userid);
            //获取风险值
            $ret = $dis->assess($userinfo);

            //因素解析+危险因素解读+生活建议
            $yinsu = $dis->yinsujiedu($userinfo, $items);
            //
            //获取营养饮食建议
            $yingyang = new YingYangService();
            $meal_arr = $yingyang->getMealCollocation($userinfo);


            //save the tag to the evaluate_human_health_tag

//
//            $resolve = $dis->getAdvice($userinfo);
            $dis_detail = EvaluateDiseaseType::model()->findByPk($disid);
//            $suggestion_ret = EvaluateMultiSuggestion::model()->findByAttributes(array("diseaseid" => $disid));
//            $item_arr = array();
//            $humheatag_ret = EvaluateHumanHealthTag::model()->findByPk($userid);
//            if (!empty($humheatag_ret->badtags)) {
//                $item_arr = explode(',', $humheatag_ret->badtags);
//            }
//            $sugserice_ins = new SuggestionService();
//
//            $sports_sug_arr = $sugserice_ins->getSportsSuggestion($userid, $item_arr);
//            $nutrition_sug_arr = $sugserice_ins->getNutritionSuggestion($userid, $item_arr);
//            $nutrition_program = EvaluateNutritionProgram::model()->findByAttributes(array("diseaseid" => $disid));

            $this->render("assess", array("result" => $ret,
                'yinsu' => $yinsu,
                "disdetail" => $dis_detail,
                "uid" => $userid, "disid" => $disid, "token" => $token));
        }
    }


    private function getDisType($disid)
    {
        $type = "";
        switch ($disid) {
            case 1:
                $type = "高血压";
                break;
            case 2:
                $type = "冠心病";
                break;
            case 3:
                $type = "脑卒中";
                break;
            case 4:
                $type = "糖尿病";
                break;
            default:
                $type = "未知";
                break;
        }
        return $type;
    }

    /**
     * 营养方案
     */
    public function actionNutritionlist()
    {
        $result = $this->diseaseService->getNutritionList($_GET);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /**
     * 营养方案项目详情
     */
    public function actionNutritionItem()
    {
        $result = $this->diseaseService->getNutritionItem($_GET);
        if (is_int($result)) {
            echo "错误的请求";
            return;
        }
        $this->render("nutrition_item", array("item" => $result));
    }

    /**
     * return to the index page from result page
     * Enter description here ...
     */
    public function actionListOut()
    {
        $result = $this->diseaseService->getList();

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /**
     * remove the old question answer,
     * Enter description here ...
     */
    public function questionAgain()
    {
        if (isset($_GET['uid'])) {
            $userid = $_GET['uid'];
        } else {
            return 0;
        }
        if (isset($_GET['disid'])) {
            $disid = $_GET['disid'];
        } else {
            return 0;
        }

        $ret = Disease::deleteUserInfo($userid, $disid);
        $hum_ret = new EvaluateHumanHealthTag();
        $hum_ret->clearTabs($userid, "badtags");
    }

}
